package 力扣._18_四数之和;

import java.util.*;

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> r = new ArrayList<>();
        int len = nums.length;

        Arrays.sort(nums);

        for (int i = 0; i < len - 3; i++) {
            // 去重
            if (i > 0 && nums[i] == nums[i - 1])
                continue;
            // 剪枝
            if ((long) nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target)
                break;
            for (int j = i + 1; j < len - 2; j++) {
                // 去重
                if (j > i+1 && nums[j] == nums[j - 1])
                    continue;
                // 剪枝
                if ((long) nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target)
                    break;
                // 剪枝
                if ((long) nums[i] + nums[j] + nums[len-2] + nums[len-1] < target)
                    continue;
                for (int m = j + 1, n = len - 1; m < n; ) {
                    long t = (long) nums[i] + nums[j] + nums[m] + nums[n];
                    if (target == t) {
                        List<Integer> list = new ArrayList<>(Arrays.asList(nums[i], nums[j], nums[m], nums[n]));
                        r.add(list);

                        // 去重
                        while (m<n&&nums[m]==nums[m+1]){
                            m++;
                        }
                        m++;
                        while (m<n&&nums[n]==nums[n-1]){
                            n--;
                        }
                        n--;

                    } else if (target > t) {
                        m++;
                    } else {
                        n--;
                    }

                }

            }
        }

        return r;

    }

    public static void main(String[] args) {
        List<List<Integer>> lists = new Solution().fourSum(
                new int[]{0, 0, 0, -1000000000, -1000000000, -1000000000, -1000000000},
                -1000000000
        );
        for (List<Integer> list : lists) {
            System.out.println(list);
        }
    }
}